package cn.wolfcode.wolf2w.service.impl;

import ch.qos.logback.classic.db.DBAppender;
import ch.qos.logback.classic.db.DBHelper;
import cn.wolfcode.wolf2w.domain.Destination;
import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.domain.Travel;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.exception.LogincException;
import cn.wolfcode.wolf2w.query.TravelCondition;
import cn.wolfcode.wolf2w.query.TravelQuery;
import cn.wolfcode.wolf2w.repository.DestinationRepository;
import cn.wolfcode.wolf2w.repository.TravelRepository;
import cn.wolfcode.wolf2w.service.IDestinationService;
import cn.wolfcode.wolf2w.service.ITravelService;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.expression.spel.ast.NullLiteral;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.lang.annotation.Target;
import java.time.DayOfWeek;
import java.util.Date;
import java.util.List;

@Service
public class TravelServiceImpl implements ITravelService {

    @Autowired
    private MongoTemplate template;

    @Autowired
    private TravelRepository repository;

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private IDestinationService destinationService;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(Travel travel) {
        travel.setId(null);
        repository.save(travel);
    }

    @Override
    public void update(Travel travel) {
        repository.save(travel);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public Travel get(String id) {
        Travel travel =repository.findById(id).orElse(null);
        if (travel!=null){
            travel.setAuthor(userInfoService.get(travel.getUserId()));
            travel.setDest(destinationService.get(travel.getDestId()));
        }
        return travel;
    }

    @Override
    public List<Travel> list() {
        return repository.findAll();
    }

    @Override
    public Page<Travel> query(TravelQuery qo) {
        //游记分页查询
        //查询对象
        //1: 查询总数:total
        Query query = new Query();
        long total = template.count(query, Travel.class);
        if (StringUtils.hasLength(qo.getDestId())){
            query.addCriteria(Criteria.where("destId").is(qo.getDestId()));
        }
        if(total == 0){
            return Page.empty();  //空的分页对象
        }
       /* if (StringUtils.hasLength(qo.getState())){
            query.addCriteria(Criteria.where("state").is(qo.getState()));
        }*/
        TravelCondition day = qo.getDay();
        if (day !=null){
            query.addCriteria(Criteria.where("day").gte(day.getMin()).lte(day.getMax()));
        }
        TravelCondition  perExpend = qo.getPerExpend();
        if (perExpend !=null){
            query.addCriteria(Criteria.where("perExpend").gte(perExpend.getMin()).lte(perExpend.getMax()));
        }

        //2: 每页显示条数集合: list
        //设置页面显示条数, 还有当前页
        //1 当前页 2 每页的条数 3 排序规则 4 排序字段
        PageRequest pageable=null;
        if(qo.getOrderType()== 2){
            pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(),
                    Sort.Direction.ASC, "viewnum");
        }else if (qo.getOrderType()==1){
            pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(),
                    Sort.Direction.ASC, "releaseTime");
        }else {
            pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(),
                    Sort.Direction.ASC, "_id");
        }
        query.with(pageable);
        List<Travel> list = template.find(query, Travel.class);
        PageImpl<Travel> page = new PageImpl<>(list, pageable, total);
        for (Travel travel : page) {
            travel.setAuthor(userInfoService.get(travel.getUserId()));
        }
        //3:封装page对象
        return page;
    }

    @Override
    public void saveOrUpdate(Travel travel) {
        //目的地名称
        Destination destination = destinationService.get(travel.getDestId());
        travel.setDestName(destination.getName());
        //用户id

        //最后跟新时间
        travel.setLastUpdateTime(new Date());
        //有id进行更新操作
        if(StringUtils.hasLength(travel.getId())){
//查询
            Travel travel1 = this.get(travel.getId());
            //替换
            travel.setViewnum(travel1.getViewnum());
            travel.setReplynum(travel1.getReplynum());
            travel.setFavornum(travel1.getFavornum());
            travel.setThumbsupnum(travel1.getThumbsupnum());
            travel.setCreateTime(travel1.getCreateTime());

            this.update(travel);
        }else {
            //添加
            //创建时间
            travel.setCreateTime(new Date());
            this.save(travel);
        }
    }
    /**
     * 改变游记的状态
     * @param id   游记的id
     * @param state   要改变的状态
     */
    @Override
    public void chenagState(int state, String id) {
        Travel travel= this.get(id);
        travel.setState(state);
        this.update(travel);
    }

    @Override
    public void audit(String id, int state) {
        //判断是否满足审核条件
        Travel travel = this.get(id);
        if(travel==null){
            throw new LogincException("参数异常");
        }
        if(travel.getState() !=Travel.STATE_WAITING){
            throw  new LogincException("当前游记不是待审核状态,不能审核");
        }
        //审核通过
        if(state ==Travel.STATE_RELEASE){
            //2 就是 修改状态为审核通过状态
            travel.setState(Travel.STATE_RELEASE);
            //修改发布时间
            travel.setReleaseTime(new Date());
            //最后更新时间
            travel.setLastUpdateTime(new Date());
            //记录审核信息
            this.update(travel);
        }else {
            //如果审核拒绝后 修改审核通过状态
            travel.setState(Travel.STATE_REJECT);
            //修改发布时间
            travel.setReleaseTime(null);
            //修改最后更新时间
            travel.setLastUpdateTime(new Date());
            this.update(travel);

        }
    }

    @Override
    public List<Travel> viewnumTop3(String destId) {
        //目的地id指定了 点击量倒数 截热门三个
        PageRequest pageRequest = PageRequest.of(0, 3, Sort.Direction.DESC, "viewnum");
        List<Travel> list = repository.findByDestId(destId, pageRequest);
        return   list;
    }

    @Override
    public List<Travel> queryByDestName(String keyword) {
        List<Travel> travels = repository.queryByDestName(keyword);
        for (Travel travel : travels) {
            UserInfo userInfo = userInfoService.get(travel.getUserId());
            travel.setAuthor(userInfo);
        }
        return travels;
    }


}
